﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Win32;

namespace EasyNotepad
{
    class HardDriveFileStorageService : IFileStorageService
    {

        class HardDriveFile : StorageFile
        {

            internal string fullFileName;

            public HardDriveFile(string name, string fullFileName) 
                : base(name)
            {
                this.fullFileName = fullFileName;
            }
        }

        public Tuple<StorageFile, Stream> OpenFile()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            bool? value = dialog.ShowDialog();
            if (value.HasValue && value.Value)
                return new Tuple<StorageFile, Stream>(new HardDriveFile(Path.GetFileName(dialog.SafeFileName), dialog.FileName), dialog.OpenFile());
            else
                return null;
        }

        public StorageFile SaveAs(Stream content)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            bool? value = dialog.ShowDialog();
            if (value.HasValue && value.Value)
            {
                Stream stream = dialog.OpenFile();
                content.CopyTo(stream);
                return new HardDriveFile(Path.GetFileName(dialog.SafeFileName), dialog.FileName);
            }
            else
                return null;
        }

        public StorageFile Save(Tuple<StorageFile, Stream> file)
        {
            HardDriveFile hdFile;
            if (file.Item1.GetType() == typeof(HardDriveFile))
            {
                hdFile = (HardDriveFile)file.Item1;
            }
            else
            {
                throw new ArgumentException("invalid file type!", "file.Item1");
            }
            try
            {
                Stream stream = File.OpenWrite(hdFile.fullFileName);
                file.Item2.CopyTo(stream);
                return file.Item1;
            }
            catch (IOException)
            {
                //Failed to access file!
                SaveFileDialog dialog = new SaveFileDialog();
                try
                {
                    dialog.FileName = hdFile.fullFileName;
                }
                catch
                { }

                bool? value = dialog.ShowDialog();

                if (value.HasValue && value.Value)
                {
                    Stream stream = dialog.OpenFile();
                    file.Item2.CopyTo(stream);
                    return new HardDriveFile(Path.GetFileName(dialog.SafeFileName), dialog.FileName);
                }
                else
                    return null;
            }
        }
    }
}
